<template>
  <a-spin tip="Loading..." :spinning="spinning">
    <div class="operation-box">
      <a-form :form="form" @submit="handleSubmit">
        <a-form-item label="小区名称" v-bind="col">
          <a-input placeholder="请输入小区名称" v-decorator="['name',{rules:[{required:true,message:'小区名称不可为空'}]}]"/>
        </a-form-item>
        <a-form-item label="所在地区" v-bind="col">
          <a-cascader :options="city" placeholder="请选择所在地区" v-decorator="['area',{rules:[{required:true,message:'所在地区不可为空'}]}]" />
        </a-form-item>
        <a-form-item label="详细地址" v-bind="col">
          <a-input placeholder="请输入详细地址" v-decorator="['address',{rules:[{required:true,message:'详细地址不可为空'}]}]"/>
        </a-form-item>
        <a-form-item label="客服电话" v-bind="col" extra="注：如有多个请使用英文逗号隔开">
          <a-input placeholder="电话号码格式：区号-号码" v-decorator="['tel']"/>
        </a-form-item>
        <a-form-item label="负责人" v-bind="col">
          <a-input placeholder="请输入负责人姓名" v-decorator="['contact']"/>
        </a-form-item>
        <a-form-item label="负责人电话" v-bind="col">
          <a-input placeholder="请输入负责人电话" v-decorator="['phone',{rules:[{pattern:/^1[3456789]\d{9}$/,message:'请输入正确负责人手机号'}]}]"/>
        </a-form-item>
        <a-form-item label="联系人" v-bind="col">
          <a-input placeholder="请输入联系人姓名" v-decorator="['call_name']"/>
        </a-form-item>
        <a-form-item label="联系人电话" v-bind="col">
          <a-input placeholder="请输入联系人电话" v-decorator="['call_tel',{rules:[{pattern:/^1[3456789]\d{9}$/,message:'请输入正确联系人手机号'}]}]"/>
        </a-form-item>
        <a-form-item label="小区logo" v-bind="col" extra="注：该图片建议尺寸320 x 320px，支持.jpg、.jpeg、.png格式，小于2M。">
          <a-upload class="operation-file-uploader" name="file" accept="image/*" listType="picture-card" :action="baseURL + 'community/uploadPic?token=' + token()" @preview="imgPreview" v-decorator="['logo_file',{initialValue:[],valuePropName:'fileList',getValueFromEvent:imageUpload}]">
            <div v-if="typeof form.getFieldValue('logo_file') === 'undefined' || form.getFieldValue('logo_file').length < 1">
              <a-icon type="plus" />
              <div class="ant-upload-text">上传图片</div>
            </div>
          </a-upload>
          <a-modal :visible="imagePreviewVisible" :footer="null" @cancel="() => { imagePreviewVisible = false }">
            <img alt="example" style="width: 100%" :src="previewImage" />
          </a-modal>
        </a-form-item>
        <a-form-item label="背景图" v-bind="col" extra="注：该图片建议尺寸 1600 x 1000px，支持.jpg .jpeg .png 格式，小于2M">
          <a-upload class="operation-file-uploader" name="file" accept="image/*" listType="picture-card" :action="baseURL + 'community/uploadPic?token=' + token()" @preview="imgPreview" v-decorator="['bg_img',{initialValue:[],valuePropName:'fileList',getValueFromEvent:imageUpload}]">
            <div v-if="typeof form.getFieldValue('bg_img') === 'undefined' || form.getFieldValue('bg_img').length < 1">
              <a-icon type="plus" />
              <div class="ant-upload-text">上传图片</div>
            </div>
          </a-upload>
          <a-modal :visible="imagePreviewVisible" :footer="null" @cancel="() => { imagePreviewVisible = false }">
            <img alt="example" style="width: 100%" :src="previewImage" />
          </a-modal>
        </a-form-item>
        <a-form-item :wrapperCol="{xs:{span:24,offset:0},sm:{span:24,offset:8}}">
          <a-button type="primary" html-type="submit">下一步</a-button>
          <a-button style="margin-left: 16px;" @click="() => { $router.go(-1) }">返回</a-button>
        </a-form-item>
      </a-form>
    </div>
  </a-spin>
</template>

<script>
  import { mapGetters } from 'vuex'
  export default {
    name: 'data_community_operation',
    data() {
      return {
        city:this.$store.state.app.city, // 省市县
        baseURL:this.axios.defaults.baseURL,
        spinning:false,
        form:this.$form.createForm(this),
        col:{
          labelCol:{xs:{span:24},sm:{span:8}},
          wrapperCol:{xs:{span:24},sm:{span:10}}
        },
        logo_fileList:[], // 小区logo
        bg_fileList:[], // 背景图
        previewImage:'', // 图片预览
        imagePreviewVisible:false,
        id:'', // 小区id
      }
    },
    async mounted() {
      let { id } = this.$route.params;
      this.id = id === 'add' ? 0 : id;
      if(!isNaN(this.id)){
        if(this.id !== 0) {
          let data = await this.getInfo(id);
          let { name,area,address,tel,contact,phone,call_name,call_tel,logo_file,bg_img } = data;
          this.form.setFieldsValue({name,area,address,tel,contact,phone,call_name,call_tel,logo_file,bg_img});
        }
      }else this.$router.go(-1);
    },
    methods:{
      ...mapGetters(['token', 'pmsArId', 'nowMg']),
      // 获取小区设置信息
      getInfo(id) {
        return new Promise((resolve,reject) => {
          this.axios({
            method:'post',
            url:'/community/getBdInfo',
            data:{id,token:this.token()}
          }).then(res => {
            let { code,msg,data } = res;
            if(code === 0){
              data.area = data.area.split(',');
              data.area = data.area.map(item => Number(item));
              for(let item of data.logo_file) item.url = this.baseURL + 'static/uploads/' + item.url;
              for(let item of data.bg_img) item.url = this.baseURL + 'static/uploads/' + item.url;
              resolve(data);
            }else this.$message.warning(msg);
          }).catch(err => {
            this.$message.error('服务器发生错误...');
          })
        })
      },
      // 提交信息
      handleSubmit(e) {
        e.preventDefault();
        this.form.validateFields((err, values) => {
          if (err) {
            for(let key in err){
              for(let item of err[key]['errors']) return this.$message.warning(item['message'],2);
            }
          }
          values.area=values.area.join(',')
          Object.assign(values,{token:this.token(),logo_file:this.$common.isEmpty(values.logo_file) ? 0 : values.logo_file[0]['uid'],bg_img:this.$common.isEmpty(values.bg_img) ? 0 : values.bg_img[0]['uid'],id:this.id});
          this.spinning = true;
          this.axios({
            method:'post',
            url:'/community/operation',
            data:values,
          }).then(res => {
            this.spinning = false;
            if(res.code == 0){
              this.$message.success('保存成功',1);
              this.$router.push({name:'data_community_extend',params:{id:res.data}})
            }else this.$message.warning(res.msg);
          }).catch(() => {this.$message.error('服务器发生错误...',2);this.spinning = false;});
        });
      },
      // 图片大小验证
      checkImage(file) {
        if((file.size / 1024 / 1024) > 2) {
          this.$message.warning('图片最大不可超过2M',2);
          return false;
        }
      },
      // 上传图片
      imageUpload({file,fileList}) {
        if((file.size / 1024 / 1024) > 2) {
          this.$message.warning('图片最大不可超过2M',2);
          return [];
        }
        if(file.status === 'removed') return [];
        if(file.status === 'uploading') return fileList;
        if(file.status === 'done'){
          let { code,msg,data } = file.response;
          if(code === 0){
            this.$message.success(msg,1);
            return [{uid:data.id,name:data.file_name,url:this.baseURL+'static/uploads/'+data.url}]
          }else {
            this.$message.error(msg,1);
            return [];
          }
        }
        if(file.status === 'error'){
          this.$message.error('上传失败',1);
          return [];
        }
      },
      // 图片预览
      imgPreview(info) {
        this.previewImage = info.url || info.thumbUrl
        this.imagePreviewVisible = true
      }
    }
  }
</script>

<style>

</style>
<style lang="less" scoped>
  .operation-box{
    background: #ffffff;
    padding:25px;
    box-sizing: border-box;
    .ant-upload-select-picture-card i {
      font-size: 32px;
      color: #999;
    }
    .ant-upload-select-picture-card .ant-upload-text {
      margin-top: 8px;
      color: #666;
    }
  }
</style>